#include "PublicUtils.h"
#include "CommandToken.h"
#include <header.h>
#include "Global.h"
#include "Constants.h"

/* 随机生成一个16位的字符串 */
void generateRandomString(char *str, size_t length) {
   srand(time(NULL));
   const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   size_t charsetSize = sizeof(charset) - 1;

   for (size_t i = 0; i < length; i++) {
      int key = rand() % charsetSize;
      str[i] = charset[key];
   }
   str[length] = '\0';  // 确保字符串以null字符结尾
}


/**
 * @brief 字符串去除首尾空格和换行
 * @param str 
*/
void trim(char *str) {
    int start = 0, end = strlen(str) - 1;

    // 找到第一个非空格和非换行符的位置
    while (isspace(str[start]) || str[start] == '\n')
        start++;

    // 找到最后一个非空格和非换行符的位置
    while (end > start && (isspace(str[end]) || str[end] == '\n'))
        end--;

    // 将字符串前移
    memmove(str, str + start, end - start + 1);

    // 在字符串末尾添加空字符
    str[end - start + 1] = '\0';

}


/* 添加epoll监听 */
int addEpoll(int epoll_fd, int fd){
	struct epoll_event event_socket;
	event_socket.events = EPOLLIN;			/* 读取 */
	event_socket.data.fd = fd;	/* 指定文件描述符 */
	epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &event_socket);

   return 0;
}

/**
 * @brief 边缘触发，且检测对方是否已关闭或半关闭
*/
int addEpoll2(int epoll_fd, int fd){
	struct epoll_event event_socket;
	/* EPOLLRDHUP 对端关闭连接（被动），或者套接字处于半关闭状态（主动），这个事件会被触发。当使用边缘触发模式时，很方便写代码测试连接的对端是否关闭了连接。 */
   event_socket.events = EPOLLIN | EPOLLRDHUP | EPOLLET;			
	event_socket.data.fd = fd;	/* 指定文件描述符 */
	epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &event_socket);

   return 0;
}


/* 删除epoll监听 */
int epollRemove(int epoll_fd, int fd){
   epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, NULL);
   return 0;
}

int getValueByKeyFromConfig(char *key, char *value) {
   FILE *file = fopen("config/config.ini", "r");
	while (1) {
		char line[100];
      memset(line,0,sizeof(line));
		// 读一行数据
		char *res = fgets(line, sizeof(line), file);
		if (res == NULL) {
			char buf[] = "没有要找的内容 \n";
			memcpy(value, buf, strlen(buf));
			return -1;
		}
		// 处理数据
		char *line_key = strtok(line, "=");
		if (strcmp(key, line_key) == 0) {
			// 要找的内容
			char *line_value = strtok(NULL, "=");
			memcpy(value, line_value, strlen(line_value) - 1);
			return 0;
		}
	}

	return 0;
}


char *getIpFromConfig(){
   char *ip = (char *)calloc(100, sizeof(char));
   getValueByKeyFromConfig("ip",ip);
   return ip;
}

char *getPortFromConfig() {
   char *port = (char *)calloc(100, sizeof(char));
   getValueByKeyFromConfig("port",port);
   return port;
}


/* 存储Token到本地 */
void saveToken(char *token){
   int fd = open("token", O_CREAT | O_WRONLY | O_TRUNC, 0664);
   write(fd, token, strlen(token));
}

/**
 * @brief 读取本地token
 * @return 0 无token
 * @return 1 有token,无需手动管理内存
*/
int readToken(){
   int fd = open("token", O_RDONLY);
   if(fd == -1){
      printf("无token\n");
      /* 本地无token */
      return 0;
   }

   memset(token, 0, BUFF_SIZE);
   int byte = read(fd, token, BUFF_SIZE);

   if(byte == 0){
      return 0;
   }
   
   return 1;

}


/**
 * @brief 接收指定字节个数
 * @return 1 接收成功
 * @return 0 对方断线
*/
int recvn(int netfd, void *buf, long length){
	ssize_t recived = 0;
	while (recived != length){
		ssize_t byte = recv(netfd, buf, length - recived, MSG_WAITALL);
        if(byte == 0){
            return 0;
        }
        // printf("recived %ld\n", recived);
		recived += byte;
	}
	return 1;
}